package com.ruoyi.system.service.impl;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.RyFileCreate;
import com.ruoyi.system.service.IRyFileCreateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.RyFileSendHistoryMapper;
import com.ruoyi.system.domain.RyFileSendHistory;
import com.ruoyi.system.service.IRyFileSendHistoryService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-02
 */
@Service
public class RyFileSendHistoryServiceImpl implements IRyFileSendHistoryService 
{

    private static final Logger LOGGER = LoggerFactory.getLogger(RyFileSendHistoryServiceImpl.class);
    @Autowired
    private RyFileSendHistoryMapper ryFileSendHistoryMapper;
    @Autowired
    private IRyFileCreateService ryFileCreateService;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public RyFileSendHistory selectRyFileSendHistoryById(Long id)
    {
        return ryFileSendHistoryMapper.selectRyFileSendHistoryById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param ryFileSendHistory 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<RyFileSendHistory> selectRyFileSendHistoryList(RyFileSendHistory ryFileSendHistory)
    {
        return ryFileSendHistoryMapper.selectRyFileSendHistoryList(ryFileSendHistory);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param ryFileSendHistory 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertRyFileSendHistory(RyFileSendHistory ryFileSendHistory)
    {
        ryFileSendHistory.setCreateTime(DateUtils.getNowDate());
        if (!CollectionUtils.isEmpty(ryFileSendHistory.getFileIds())){
            for (Long fileId : ryFileSendHistory.getFileIds()) {
                RyFileCreate ryFileCreate = ryFileCreateService.selectRyFileCreateById(fileId);
                ryFileSendHistory.setFileId(fileId);
                ryFileSendHistory.setFileName(ryFileCreate.getName());
                ryFileSendHistory.setCreateBy(SecurityUtils.getUserId().toString());
                ryFileSendHistory.setCreateTime(DateUtils.getNowDate());
                ryFileSendHistory.setUpdateBy(SecurityUtils.getUserId().toString());
                ryFileSendHistory.setUpdateTime(DateUtils.getNowDate());
                File file = new File(ryFileCreate.getPath());
                if (!file.exists()){
//                    throw new RuntimeException("无此文件");
                    ryFileSendHistory.setMsg("无此文件");
                }
                else {
                    JSONObject jsonObject = new JSONObject().fluentPut("fileName", ryFileCreate.getName()).fluentPut("sendSysCode", ryFileSendHistory.getSendSysCode()).fluentPut("recvSysCode", ryFileSendHistory.getRecvSysCode()).fluentPut("uploadPath",file.getParent().replace("\\","/"));
                    String res = HttpUtils.sendPost("http://10.14.106.103:8091/put",jsonObject.toJSONString(),MediaType.APPLICATION_JSON_VALUE);
                    LOGGER.info("文件发送接口返回:{}",res);
                    if (StringUtils.isNotEmpty(res)){
                        try {
                            JSONObject reponse = JSON.parseObject(res);
                            ryFileSendHistory.setFlag(reponse.getInteger("code").toString());
                            if (reponse.getInteger("code")==200){
                                ryFileSendHistory.setMsg("成功");
                            }else {
                                ryFileSendHistory.setMsg("失败");
                            }
                            if (StringUtils.isNotEmpty(reponse.getJSONObject("info"))){
                                ryFileSendHistory.setInfo(reponse.getJSONObject("info").toJSONString());
                            }
                        }catch (Exception e){
                            ryFileSendHistory.setMsg("失败");
                        }
                    }
                }
                ryFileSendHistoryMapper.insertRyFileSendHistory(ryFileSendHistory);
            }
            return 1;
        }else {
            insertRyFileSendHistoryBath(ryFileSendHistory);
        }
        return 1;
    }

    @Override
    public int insertRyFileSendHistoryBath(RyFileSendHistory ryFileSendHistory) {
        if (StringUtils.isNotEmpty(ryFileSendHistory.getInputPath())){
            List<String> filesInFolder = getFilesInFolder(ryFileSendHistory.getInputPath());
            if (!CollectionUtils.isEmpty(filesInFolder)){
                for (String filename : filesInFolder) {
                    ryFileSendHistory.setCreateBy(SecurityUtils.getUserId().toString());
                    ryFileSendHistory.setCreateTime(DateUtils.getNowDate());
                    ryFileSendHistory.setUpdateBy(SecurityUtils.getUserId().toString());
                    ryFileSendHistory.setUpdateTime(DateUtils.getNowDate());
                    ryFileSendHistory.setFileName(filename);
                    JSONObject jsonObject = new JSONObject().fluentPut("fileName", filename).fluentPut("sendSysCode", ryFileSendHistory.getSendSysCode()).fluentPut("recvSysCode", ryFileSendHistory.getRecvSysCode()).fluentPut("uploadPath",ryFileSendHistory.getInputPath());
                    LOGGER.info("文件发送接口入参:{}",jsonObject);
                    String res = HttpUtils.sendPost("http://10.14.106.103:8091/put",jsonObject.toJSONString(),MediaType.APPLICATION_JSON_VALUE);
                    LOGGER.info("文件发送接口返回:{}",res);
                    if (StringUtils.isNotEmpty(res)){
                        try {
                            JSONObject reponse = JSON.parseObject(res);
                            ryFileSendHistory.setFlag(reponse.getInteger("code").toString());
                            if (reponse.getInteger("code")==200){
                                ryFileSendHistory.setMsg("成功");
                            }else {
                                ryFileSendHistory.setMsg("失败");
                            }
                            if (StringUtils.isNotEmpty(reponse.getJSONObject("info"))){
                                ryFileSendHistory.setInfo(reponse.getJSONObject("info").toJSONString());
                            }
                        }catch (Exception e){
                            ryFileSendHistory.setMsg("失败");
                        }
                    }
                    ryFileSendHistoryMapper.insertRyFileSendHistory(ryFileSendHistory);
                }

            }
        }
        return 1;
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param ryFileSendHistory 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateRyFileSendHistory(RyFileSendHistory ryFileSendHistory)
    {
        ryFileSendHistory.setUpdateBy(SecurityUtils.getUserId().toString());
        ryFileSendHistory.setUpdateTime(DateUtils.getNowDate());
        return ryFileSendHistoryMapper.updateRyFileSendHistory(ryFileSendHistory);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteRyFileSendHistoryByIds(Long[] ids)
    {
        return ryFileSendHistoryMapper.deleteRyFileSendHistoryByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteRyFileSendHistoryById(Long id)
    {
        return ryFileSendHistoryMapper.deleteRyFileSendHistoryById(id);
    }

    /**
     * 获取指定文件夹下的所有文件路径（不包含子文件夹）
     * @param folderPath 文件夹路径
     * @return 文件路径列表
     */
    public List<String> getFilesInFolder(String folderPath) {
        File folder = new File(folderPath);

        if (!folder.exists() || !folder.isDirectory()) {
            System.err.println("错误：文件夹不存在或不是有效文件夹 - " + folderPath);
            return new ArrayList<>();
        }

        File[] files = folder.listFiles();
        if (files == null) {
            return new ArrayList<>();
        }

        return Arrays.stream(files)
                .filter(File::isFile)
                .map(File::getName)
                .collect(Collectors.toList());
    }

}
